<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VideoCamera, Edit, Money, Lock } from '@element-plus/icons-vue'
import { profile, updateProfile, recharge, resetPassword } from '@/api/user'
import { uploadImage } from '@/api/upload'

const router = useRouter()

const user = ref(null)
const loading = ref(false)
const saving = ref(false)

// 编辑表单（与后端可更新字段保持一致）
const form = ref({
  phone: '',
  email: '',
  avatarUrl: '',
  bio: '',
})

const balanceText = computed(() => {
  const b = user.value?.balance
  if (!b) return '¥ 0.00'
  try {
    const n = typeof b === 'number' ? b : Number(b)
    return `¥ ${n.toFixed(2)}`
  } catch { return `¥ ${b}` }
})

const displayName = computed(() => {
  const u = user.value
  return u?.nickname || u?.username || u?.uname || u?.name || '影迷'
})
const avatarSrc = computed(() => (form.value.avatarUrl || user.value?.avatar || user.value?.avatarUrl || user.value?.imageUrl || user.value?.photo || user.value?.portrait))

// 本地头像上传
const uploading = ref(false)
const handleAvatarUpload = async (param) => {
  const file = param?.file
  if (!file) return
  uploading.value = true
  try {
    const res = await uploadImage(file)
    if (res.code === '200') {
      form.value.avatarUrl = res.data
      ElMessage.success('头像上传成功')
      await saveProfile()
    } else {
      ElMessage.error(res.msg || '上传失败')
    }
  } catch {} finally {
    uploading.value = false
  }
}

// 复制头像地址
const copyAvatarUrl = async () => {
  const url = form.value.avatarUrl
  if (!url) {
    ElMessage.warning('暂无头像地址')
    return
  }
  try {
    await navigator.clipboard.writeText(url)
    ElMessage.success('已复制头像地址')
  } catch (e) {
    ElMessage.error('复制失败，请手动选择文本复制')
  }
}

const rechargeVisible = ref(false)
const rechargeAmount = ref(50)

const loadUser = async () => {
  loading.value = true
  try {
    const res = await profile()
    if (res.code === '200') {
      user.value = res.data
      form.value.phone = user.value?.phone || ''
      form.value.email = user.value?.email || ''
      form.value.avatarUrl = user.value?.avatarUrl || ''
      form.value.bio = user.value?.bio || ''
    } else {
      ElMessage.error(res.msg || '获取个人信息失败')
      router.push('/login')
    }
  } catch {
    router.push('/login')
  } finally {
    loading.value = false
  }
}

const saveProfile = async () => {
  saving.value = true
  try {
    const res = await updateProfile(form.value)
    if (res.code === '200') {
      ElMessage.success('保存成功')
      await loadUser()
    } else {
      ElMessage.error(res.msg || '保存失败')
    }
  } catch {} finally {
    saving.value = false
  }
}

const doRecharge = async () => {
  if (!rechargeAmount.value || rechargeAmount.value <= 0) {
    ElMessage.warning('请输入有效的充值金额')
    return
  }
  try {
    const res = await recharge({ amount: rechargeAmount.value })
    if (res.code === '200') {
      ElMessage.success('充值成功')
      rechargeVisible.value = false
      await loadUser()
    } else {
      ElMessage.error(res.msg || '充值失败')
    }
  } catch {}
}

const doResetPassword = async () => {
  try {
    await ElMessageBox.confirm('确认将密码重置为默认值 123456？', '重置密码', { type: 'warning' })
  } catch { return }
  try {
    const res = await resetPassword()
    if (res.code === '200') {
      ElMessage.success('密码已重置为 123456')
    } else {
      ElMessage.error(res.msg || '重置失败')
    }
  } catch {}
}

const goHome = () => router.push('/')

onMounted(() => {
  loadUser()
})
</script>

<template>
  <div class="page profile" v-loading="loading">
    <!-- 顶部导航 -->
    <div class="topbar">
      <div class="brand" @click="goHome">
        <el-icon><VideoCamera /></el-icon>
        <span>个人信息</span>
      </div>
      <div class="actions">
        <el-link type="primary" @click="goHome">首页</el-link>
      </div>
    </div>

    <!-- 英雄区：标题 -->
    <section class="hero glass">
      <h1 class="title">个人信息</h1>
      <p class="subtitle">编辑联系方式与头像，支持账户充值与重置密码</p>
    </section>

    <!-- 内容区：资料编辑 -->
    <section class="content">
      <div class="grid">
        <el-card class="info-card" shadow="hover">
          <div class="info-header">
            <div class="avatar-box">
              <el-avatar :src="avatarSrc" :size="64">{{ displayName.slice(0,1) }}</el-avatar>
            </div>
            <div class="user-basic">
              <div class="name-row">
                <div class="name">{{ displayName }}</div>
                <span class="balance-pill">{{ balanceText }}</span>
              </div>
              <div class="hint">完善联系方式，支持本地上传头像</div>
            </div>
            <div class="upload-area">
              <el-upload :show-file-list="false" :http-request="handleAvatarUpload" accept="image/*">
                <el-button :loading="uploading">本地上传头像</el-button>
              </el-upload>
            </div>
          </div>

          <el-form :model="form" label-position="left" label-width="92px" class="form">
            <div class="form-grid">
              <el-form-item label="手机号">
                <el-input v-model="form.phone" placeholder="请输入手机号" size="large" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="form.email" placeholder="请输入邮箱" size="large" />
              </el-form-item>
              <el-form-item label="头像地址" class="col-span-2">
                <el-input v-model="form.avatarUrl" placeholder="支持外链或上传后自动填充" size="large">
                  <template #suffix>
                    <el-button link type="primary" @click="copyAvatarUrl">复制</el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="个人简介" class="col-span-2">
                <el-input v-model="form.bio" type="textarea" :rows="4" placeholder="可以写下你的电影偏好、影评风格等" />
              </el-form-item>
            </div>
            <div class="buttons">
              <el-button type="primary" :loading="saving" @click="saveProfile">
                <el-icon style="margin-right:6px"><Edit /></el-icon>
                保存信息
              </el-button>
              <el-button @click="rechargeVisible = true">
                <el-icon style="margin-right:6px"><Money /></el-icon>
                充值余额
              </el-button>
              <el-button type="warning" @click="doResetPassword">
                <el-icon style="margin-right:6px"><Lock /></el-icon>
                重置密码
              </el-button>
            </div>
          </el-form>
        </el-card>
      </div>
    </section>

    <!-- 充值弹窗 -->
    <el-dialog v-model="rechargeVisible" title="充值余额" width="420px">
      <el-form label-position="top">
        <el-form-item label="充值金额（元）">
          <el-input-number v-model="rechargeAmount" :min="1" :step="10" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rechargeVisible=false">取消</el-button>
        <el-button type="primary" @click="doRecharge">立即充值</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page.profile {
  min-height: 100vh;
  background:
    radial-gradient(1200px 600px at 15% 20%, #101317 0%, #0b0e12 40%, #06080b 100%),
    linear-gradient(180deg, #0b0f15 0%, #0d1117 100%);
}

.topbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 22px;
  color: #cfd3dc;
}
.topbar .brand { display: flex; align-items: center; gap: 10px; cursor: pointer; }
.topbar .brand span { font-weight: 600; letter-spacing: 1px; }
.topbar .actions { display: flex; gap: 14px; }

.hero.glass {
  margin: 10px auto 0;
  padding: 22px 24px;
  max-width: 1080px;
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.06);
  box-shadow: 0 12px 40px rgba(0,0,0,0.45);
  backdrop-filter: blur(8px);
  border: 1px solid rgba(255,255,255,0.12);
}
.title { color: #e5eaf3; font-size: 24px; font-weight: 600; }
.subtitle { color: #9ea5b1; margin-top: 6px; }

.content { max-width: 1080px; margin: 16px auto 40px; }
.grid { display: grid; grid-template-columns: 1fr; gap: 16px; }

.info-card { background: rgba(255,255,255,0.06); border-color: rgba(255,255,255,0.12); border-radius: 14px; }
.info-header { display: flex; align-items: center; gap: 16px; margin-bottom: 12px; }
.upload-area { margin-left: auto; }
.avatar-box { display: grid; place-items: center; }
.user-basic .name { color: #e5eaf3; font-size: 18px; font-weight: 600; }
.user-basic .balance { color: #9ea5b1; margin-top: 6px; }
.name-row { display: flex; align-items: center; gap: 10px; }
.balance-pill { color: #e5eaf3; background: rgba(46,170,88,.18); border: 1px solid rgba(46,170,88,.35); padding: 2px 10px; border-radius: 999px; font-size: 12px; }
.hint { color: #9ea5b1; font-size: 12px; margin-top: 4px; }

.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.col-span-2 { grid-column: 1 / -1; }

.form :deep(.el-form-item__label) { color: #cfd3dc; }
.form :deep(.el-input__wrapper) { background: rgba(255,255,255,0.08); border-color: rgba(255,255,255,0.12); box-shadow: none; }
.form :deep(textarea.el-textarea__inner) { background: rgba(255,255,255,0.08); color: #e5eaf3; }

.buttons { display: flex; gap: 12px; margin-top: 6px; justify-content: flex-end; }
</style>